package ejb;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import model.Member;
import model.Party;
import utils.AbstractBean;
import dto.MemberDTO;
import dto.PartyDTO;
import entitymanagers.PartyManager;

@Stateless
@LocalBean
public class PartyManagerBean extends AbstractBean<Party> implements PartyManager {

	@PersistenceContext
	private EntityManager em;
	@Resource
	private SessionContext context;
	
	public PartyManagerBean() {
		super(Party.class);
	}

	@Override
	public PartyDTO[] getParties() {
		return convertToDTO(findAll());
		
	}

	public static PartyDTO[] convertToDTO(List<Party> parties) {
		PartyDTO[] arrParties = new PartyDTO[parties.size()];
		int i = 0;
		for(Party p : parties){
			arrParties[i++] = convertToDTO(p);
		}
		return arrParties;
	}

	@Override
	public PartyDTO getPartiesByID(String partyID) {
		return convertToDTO(find(partyID));
	}

	@Override
	public PartyDTO getPartiesByName(String name) {
		return convertToDTO(find(name));
	}

	@Override
	protected EntityManager getEntityManager() {
		return em;
	}
	
	@Override
	public MemberDTO[] getMembersByParty(String idParty) {
		MemberDTO[] members;
		try{
			Party party = find(idParty);
			members = new MemberDTO[party.getMembers().size()];
			int i = 0;
			for (Member m : party.getMembers()){
				members[i++]= convertToDTO(m);
			}
		}
		catch (Exception e){
			return null;
		}return members;
	}
	private static PartyDTO convertToDTO(Party party){
		PartyDTO partyDTO = new PartyDTO();
		partyDTO.setCreator(partyDTO.getCreator());
		partyDTO.setName(partyDTO.getName());
		partyDTO.setDateCreated(partyDTO.getDateCreated());
		partyDTO.setProgram(partyDTO.getProgram());
		partyDTO.setSymbol(partyDTO.getSymbol());
		return partyDTO;
	}
	public static MemberDTO convertToDTO(Member member) {
		MemberDTO memberDTO = new MemberDTO();
		memberDTO.setCitizen(memberDTO.getCitizen());
		memberDTO.setIdMember(memberDTO.getIdMember());
		memberDTO.setIdParty(memberDTO.getIdParty());
		return memberDTO;
	}

}
